﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Order.EntityFrameworkCore
{
    /// <summary>
    /// 工作单元
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        private readonly OrderContext _dbContext;

        public UnitOfWork(OrderContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 提交
        /// </summary>
        public void Commit()
        {
            _dbContext.SaveChanges();
        }
        /// <summary>
        /// 异步提交
        /// </summary>
        /// <returns></returns>
        public async Task<bool> CommitAsync()
        {
           return await _dbContext.SaveChangesAsync(CancellationToken.None) > 0;
        }
        
        /// <summary>
        /// 内存回收
        /// </summary>
        //public void Dispose()
        //{
        //    //if (_dbContext != null)
        //    //{
        //    //    _dbContext.Dispose();
        //    //    GC.Collect();
        //    //}
        //}

        /// <summary>
        /// 保存更改前操作,可以记录日志数据
        /// </summary>
        public virtual void SaveChangesBefore()
        {
            foreach (var entry in _dbContext.ChangeTracker.Entries())
            {
                switch (entry.State)
                {
                    case EntityState.Added:

                        break;
                    case EntityState.Modified:

                        break;
                    case EntityState.Deleted:

                        break;
                }
            }
        }
    }
}
